function $Class(id) { return document.getElementsByClassName(id); }

function getArgsFromForm() {
  var currentForm = iui.getSelectedPage();
  var titleValue = currentForm.elements['dc-title'].value;
  var descriptionValue = currentForm.elements['dc-description'].value;
  var issuedValueString = currentForm.elements['dc-issued'].value;
  var issuedValue;
  if (issuedValueString != 'Today') {
    issuedValue = (new Date(issuedValueString)).toISO8601String(6);
  } else {
    issuedValue = (new Date()).toISO8601String(6)
  }
  var typeElement = currentForm.elements['doctype'];
  var typeValue = null;
  if (typeElement != null) { typeValue = typeElement.value };
  return {'name' : titleValue, 'dc:title' : titleValue, 'dc:description' : descriptionValue, 'dc:issued' : issuedValue, 'doctype' : typeValue};
}

function getDocumentURL(docId) {
  return basePath + '/mobile/navigation/byId/' + docId;
}

function nxDeleteDocumentFormAndGoBack(docId) {
  iui.ajax(getDocumentURL(docId) + '/@delete', null, 'GET', function (xhr) {
    iui.goBackSeveralTimes(2);
  });
}


function nxUpdateDocumentFormAndGoBack(docId) {
  var args = getArgsFromForm();
  // can't make a PUT with iui.ajax
  iui.ajax(getDocumentURL(docId) + '/@put', args, 'POST', function (xhr) {
    response = xhr.responseText;
    iui.goBackSeveralTimes(2);
    // Update title in lists
    var docInList = $Class(	docId + '_nxlist');
    if (docInList != null) {
      for ( var i = 0; i < docInList.length; i++) {
        var elt = docInList[i];
        elt.innerHTML = args['dc:title'];
      }
      // TODO : put the remove on the aftertransition event
    }
    // TODO : Take care of problems that can occurs server side
  });
}

function nxPostDocumentFormAndGoBack(parentId) {
  var args = getArgsFromForm();
  if (args['doctype'] == 'LocalizedTweet') {
    addPostionAndPostDocumentFormAndGoBack(parentId, args);
  } else {
    nxDoPostDocumentFormAndGoBack(parentId, args);
  }
}

function nxDoPostDocumentFormAndGoBack(parentId, args) {
  iui.ajax(getDocumentURL(parentId), args, 'POST', function (xhr) {
  	iui.showPageByHref(getDocumentURL(parentId));
    // TODO : Add title in list
    // TODO : Take care of problems that can occurs server side
  });
}

function addPostionAndPostDocumentFormAndGoBack(docId, args) {
  navigator.geolocation.getCurrentPosition (
      function (position) {
        args['gps:latitude'] = position.coords.latitude;
        args['gps:longitude'] = position.coords.longitude;
//      	message = 'latitude : ' + position.coords.heading;
//      	message = 'latitude : ' + position.coords.speed;
//      	message = 'latitude : ' + position.coords.altitude;
        nxDoPostDocumentFormAndGoBack(docId, args);
      },
      function () {
        alert ("Can't get your localisation, tweet will be created without your localisation");
        nxDoPostDocumentFormAndGoBack(docId, args);
      });

}

function nxDoActionWithGoBackViewElements(urlAction)
{
  iui.ajax(urlAction, null, 'GET', function (xhr) {
    var response = xhr.responseText;
    if (response == 'OK') {
      iui.goBackSeveralTimes(2);
    }
  });
}

function nxDoActionWithGoBack(urlAction)
{
  iui.ajax(urlAction, null, 'GET', function (xhr) {
    var response = xhr.responseText;
    if (response == 'OK') {
      iui.goBack();
    } else {
      alert("Problem occurs : " + response);
    }

  });
}

function cleanFormValuesOnBlur() {
  iui.getSelectedPage().addEventListener("blur", function (event) {
    iui_ext.clear();
  })
}


Date.prototype.toDatePickerFormat = function() {
  return formatDate(this, 'E dd NNN, yy');
}



// taken from http://delete.me.uk/2005/03/iso8601.html thank's to him :)
Date.prototype.toISO8601String = function(format, offset) {
  /* accepted values for the format [1-6]:
   1 Year:
     YYYY (eg 1997)
   2 Year and month:
     YYYY-MM (eg 1997-07)
   3 Complete date:
     YYYY-MM-DD (eg 1997-07-16)
   4 Complete date plus hours and minutes:
     YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
   5 Complete date plus hours, minutes and seconds:
     YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
   6 Complete date plus hours, minutes, seconds and a decimal
     fraction of a second
     YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
  */
  if (!format) { var format = 6; }
  if (!offset) {
      var offset = 'Z';
      var date = this;
  } else {
      var d = offset.match(/([-+])([0-9]{2}):([0-9]{2})/);
      var offsetnum = (Number(d[2]) * 60) + Number(d[3]);
      offsetnum *= ((d[1] == '-') ? -1 : 1);
      var date = new Date(Number(Number(this) + (offsetnum * 60000)));
  }

  var zeropad = function (num) { return ((num < 10) ? '0' : '') + num; }

  var str = "";
  str += date.getUTCFullYear();
  if (format > 1) { str += "-" + zeropad(date.getUTCMonth() + 1); }
  if (format > 2) { str += "-" + zeropad(date.getUTCDate()); }
  if (format > 3) {
      str += "T" + zeropad(date.getUTCHours()) +
             ":" + zeropad(date.getUTCMinutes());
  }
  if (format > 5) {
      var secs = Number(date.getUTCSeconds() + "." +
                 ((date.getUTCMilliseconds() < 100) ? '0' : '') +
                 zeropad(date.getUTCMilliseconds()));
      str += ":" + zeropad(secs);
  } else if (format > 4) { str += ":" + zeropad(date.getUTCSeconds()); }

  if (format > 3) { str += offset; }
  return str;
}

function ProcessEvent (event, eventName, elementName, stopPropagate) {
  WriteInfo ("The " + elementName + " element got an " + eventName + " event.");
  if (stopPropagate) {
      if (event.bubbles === undefined) {  // Internet Exlorer
              // always cancel bubbling
          event.cancelBubble = true;
          WriteInfo ("The propagation of the " + eventName + " event is stopped.");
      }
      else {        // Firefox, Opera, Google Chrome and Safari
          if (event.bubbles) {
              event.stopPropagation ();
              WriteInfo ("The propagation of the " + eventName + " event is stopped.");
          }
          else {
              WriteInfo ("The " + eventName + " event cannot propagate up the DOM hierarchy.");
          }
      }
  }
}
